package com.teamwin.hdmi;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class HDMwIn extends SocketManager {// implements SensorEventListener {
	public final static int MENU_DISPLAY_OPTIONS = 0;
	public final static int MENU_ADVANCED_OPTIONS = 1;
	public final static int HDMI_NOTIFICATION = 2;
	
//    private final BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//        	System.out.println("HEADSET EVENT RECEIVED!");
//            System.out.println(intent.getExtras().get("state"));
//            System.out.println(intent.getExtras().get("name"));
//            System.out.println(intent.getExtras().get("microphone"));
////            if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
////            }
//        }
//    };
    
	public class VSyncSelectionListener implements OnItemSelectedListener {
		HDMwIn parent = null;
		
		public VSyncSelectionListener(HDMwIn parent) {
			this.parent = parent;
		}
		
	    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	    	boolean vSync = (pos == 1 ? true : false);
	        this.parent.getEditor().putBoolean("vsync", vSync);
	        this.parent.getEditor().commit();
	        
	        if (vSync != this.parent.isvSync()) {
		        this.parent.sendCommand(SET_VSYNC, pos + "");
	        }
	        this.parent.setvSync(vSync);
	    }

		@SuppressWarnings("unchecked")
		public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
	
	class ButtonListener implements View.OnClickListener {
		HDMwIn parent;
		
		public ButtonListener(HDMwIn parent) {
			this.parent = parent;
		}
		
		@Override
		public void onClick(View v) {
			boolean cablePlugged = this.parent.sendCommand(GET_CABLE_STATUS, null).equalsIgnoreCase("1");
			boolean succeeded = false;
			
			this.parent.checkSocket();
			if (!this.parent.isMirroring()) {
				if (cablePlugged) {
					String chosenRez = this.parent.getSettings().getString("resolution", "");
					if (!chosenRez.equalsIgnoreCase("")) {
						this.parent.sendCommand(HDMwIn.SET_RESOLUTION, chosenRez);
					} else {
						this.parent.sendCommand(HDMwIn.SET_RESOLUTION, null);
					}
					
					succeeded = this.parent.sendCommand(HDMwIn.ENABLE, null).equalsIgnoreCase("1"); 
//					if (succeeded) {
					NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					Notification notification = new Notification(R.drawable.notification_icon, "Click to change HDMI", System.currentTimeMillis());
					notification.defaults |= Notification.FLAG_NO_CLEAR;
					Intent notificationIntent = new Intent(this.parent, HDMwIn.class);
					PendingIntent contentIntent = PendingIntent.getActivity(this.parent, 0, notificationIntent, 0);
					notification.setLatestEventInfo(this.parent.getApplicationContext(), "HDMwIn", "Change HDMI Settings", contentIntent);

					mNotificationManager.notify(HDMI_NOTIFICATION, notification);
					
					if (!this.parent.isBannersEnabled()) {
						this.parent.sendCommand(SET_BANNER, "0");
					}
					
					Button b = (Button) findViewById(R.id.startMirroring);
					b.setText("Stop Mirroring");
					ImageView image = (ImageView) findViewById(R.id.hdmi_image_status);
			        image.setImageResource(R.drawable.appstatusenable);
			        
			        this.parent.getEditor().putBoolean("enabled", this.parent.isMirroring());
			        this.parent.getEditor().commit();
//					} else {
//						this.parent.getEditor().putBoolean("enabled", this.parent.isMirroring());
//				        this.parent.getEditor().commit();
//						Toast.makeText(this.parent, "Failed to mirror! Check your resolution.", Toast.LENGTH_SHORT).show();
//					}
				} else {
					NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					mNotificationManager.cancel(HDMI_NOTIFICATION);
					
					ImageView image = (ImageView) findViewById(R.id.hdmi_image_status);
			        image.setImageResource(R.drawable.appstatusundetected);
					Toast.makeText(this.parent, "Error: Cable is unplugged!", Toast.LENGTH_SHORT).show();
				}
			} else {
				if (cablePlugged) {
					NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					mNotificationManager.cancel(HDMI_NOTIFICATION);
					this.parent.sendCommand(HDMwIn.DISABLE, null);
					Button b = (Button) findViewById(R.id.startMirroring);
					b.setText("Start Mirroring");
					ImageView image = (ImageView) findViewById(R.id.hdmi_image_status);
			        image.setImageResource(R.drawable.appstatusdisable);
			        
			        this.parent.getEditor().putBoolean("enabled", this.parent.isMirroring());
			        this.parent.getEditor().commit();
				}
			}
			if (cablePlugged) {
				this.parent.setMirroring(!this.parent.isMirroring());
			}
		}
	}
	
	class CheckBoxListener implements View.OnClickListener {
		HDMwIn parent;
		
		public CheckBoxListener(HDMwIn parent) {
			this.parent = parent;
		}
		
		@Override
		public void onClick(View v) {
			CheckBox checkBox = (CheckBox) findViewById(R.id.autoRotate);
			boolean checked = checkBox.isChecked(); 
			RadioButton radioButton = (RadioButton) findViewById(R.id.radio0);
			radioButton.setEnabled(!checked);
			radioButton = (RadioButton) findViewById(R.id.radio1);
			radioButton.setEnabled(!checked);
			
	        this.parent.getEditor().putBoolean("auto_rotate", checked);
	        this.parent.getEditor().commit();
	        
	        this.parent.setAutoRotate(checked);
		}
	}
	
	class RadioButtonListener implements View.OnClickListener {
		HDMwIn parent;
		
		public RadioButtonListener(HDMwIn parent) {
			this.parent = parent;
		}
		
		@Override
		public void onClick(View v) {
			RadioButton radioButton = (RadioButton) findViewById(R.id.radio0);
			boolean checked = radioButton.isChecked();
			if (checked) {
				this.parent.getEditor().putString("orientation", "portrait");
				this.parent.sendCommand(HDMwIn.ROTATE_NONE, null);
			} else {
				this.parent.getEditor().putString("orientation", "landscape");
				this.parent.sendCommand(HDMwIn.ROTATE_90, null);
			}
			this.parent.getEditor().commit();
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		this.checkDaemonVersion();
		
//		IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
//		this.registerReceiver(headsetReceiver, filter);
		
		this.checkSocket();
		
//		System.out.println("Checking for kernel.");
		if (!this.hasAcceleratedKernel()) {
			startInstaller(NEED_KERNEL, -1);
		}
		
		final RadioButton radioButton1 = (RadioButton) findViewById(R.id.radio0);
		final RadioButton radioButton2 = (RadioButton) findViewById(R.id.radio1);
		RadioButtonListener radioListener = new RadioButtonListener(this);
		radioButton1.setOnClickListener(radioListener);
		radioButton2.setOnClickListener(radioListener);
		
		this.setOrientation(this.getSettings().getString("orientation", ""));
		if (this.getOrientation().equalsIgnoreCase("portrait")) {
			this.sendCommand(HDMwIn.ROTATE_NONE, null);
			radioButton1.setChecked(true);
		} else if (this.getOrientation().equalsIgnoreCase("landscape")) {
			this.sendCommand(HDMwIn.ROTATE_90, null);
			radioButton2.setChecked(true);
		}
		
		final Button enableButton = (Button) findViewById(R.id.startMirroring);
		ButtonListener listener = new ButtonListener(this);
		enableButton.setOnClickListener(listener);
		
		final CheckBox checkBox = (CheckBox) findViewById(R.id.autoRotate);
		CheckBoxListener checkBoxListener = new CheckBoxListener(this);
		checkBox.setOnClickListener(checkBoxListener);
		
		final Spinner spinner = (Spinner) findViewById(R.id.vSyncOptions);
		spinner.setOnItemSelectedListener(new VSyncSelectionListener(this));
		
		this.checkVSync();
		
//		mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
//      mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	}
	
	protected void onPause() {
        super.onPause();
	}
	
	protected void onResume() {
	//		mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	//			this.registerReceiver(this.commandReceiver, filter);
			
		CheckBox checkBox = (CheckBox) findViewById(R.id.autoRotate);
		checkBox.setChecked(this.isAutoRotate());
		
		RadioButton radioButton = (RadioButton) findViewById(R.id.radio0);
		if (this.getOrientation().equalsIgnoreCase("portrait")) {
			radioButton.setChecked(true);
		}
		radioButton.setEnabled(!this.isAutoRotate());
		radioButton = (RadioButton) findViewById(R.id.radio1);
		if (this.getOrientation().equalsIgnoreCase("landscape")) {
			radioButton.setChecked(true);
		}
		radioButton.setEnabled(!this.isAutoRotate());
		
		if (this.isMirroring()) {
			ImageView image = (ImageView) findViewById(R.id.hdmi_image_status);
	        image.setImageResource(R.drawable.appstatusenable);
	        Button b = (Button) findViewById(R.id.startMirroring);
			b.setText("Stop Mirroring");
		} else {
			Button b = (Button) findViewById(R.id.startMirroring);
			b.setText("Start Mirroring");
			ImageView image = (ImageView) findViewById(R.id.hdmi_image_status);
	        image.setImageResource(R.drawable.appstatusdisable);
		}
		this.checkVSync();
		
		super.onResume();
	}
	
	public void checkDaemonVersion() {
		HttpURLConnection urlConnection = null;
		
		try {
			URL url = new URL(versionUrl);
			urlConnection = (HttpURLConnection) url.openConnection();
			InputStream in = new BufferedInputStream(urlConnection.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line = null;
			String versionLine = null;
			while ((line = br.readLine())!= null) {
				versionLine = line;
			}
			
			int currentDaemonVersion = 0;
			String versionResult = this.sendCommand(GET_DAEMON_VERSION, null);
			if (!versionResult.equalsIgnoreCase("0")) {
				currentDaemonVersion = Integer.parseInt(versionResult.substring(1));
			}
			int latestVersion = Integer.parseInt(versionLine);
			if (currentDaemonVersion != latestVersion) {
				startInstaller(NEW_DAEMON, latestVersion);
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			urlConnection.disconnect();
		}
	}
	
	public void checkVSync() {
		Spinner spinner = (Spinner) findViewById(R.id.vSyncOptions);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.vSyncArray, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);
	    
	    boolean vSync = this.getSettings().getBoolean("vsync", true);
	    
		this.setvSync(vSync);
		spinner.setSelection((vSync ? 1 : 0));
	}
	
	public void initialSetup() {
		Button enableButton = (Button) findViewById(R.id.startMirroring);
		enableButton.setVisibility(View.GONE);
		CheckBox checkBox = (CheckBox) findViewById(R.id.autoRotate);
		checkBox.setVisibility(View.GONE);
		RadioButton radioButton = (RadioButton) findViewById(R.id.radio0);
		radioButton.setVisibility(View.GONE);
		radioButton = (RadioButton) findViewById(R.id.radio1);
		radioButton.setVisibility(View.GONE);
		ImageView imageView = (ImageView)findViewById(R.id.hdmi_image_status);
		imageView.setVisibility(View.GONE);
		TextView textView = (TextView)findViewById(R.id.hdmiOrientation);
		textView.setVisibility(View.GONE);
		
		LinearLayout layout = (LinearLayout)findViewById(R.id.hiddenLayout);
		layout.setVisibility(View.VISIBLE);
		
//		Button
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(0, MENU_DISPLAY_OPTIONS, 0, "Display Options");
//		menu.add(0, HDMwIn.MENU_ADVANCED_OPTIONS, 0, "Advanced Options");
		return true;
	}
	
	public boolean onOptionsItemSelected (MenuItem item){
		switch (item.getItemId()){
			case MENU_DISPLAY_OPTIONS:
				startActivity(new Intent(this, DisplayOptions.class));
				break;
			case MENU_ADVANCED_OPTIONS:
				startActivity(new Intent(this, Installer.class));
				break;
			default:
				break;
		}
		return true;
	}
	
//	@Override
//	public void onAccuracyChanged(Sensor sensor, int accuracy) {
//		//nothing
//	}
//	int rotation = 0;
//	@Override
//	public void onSensorChanged(SensorEvent event) {
//		System.out.println("SENSOR EVENT!");
//		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
//		try {
//			Socket socket = new Socket("127.0.0.1", 61083);
//			DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//			int rotation = display.getRotation();
//			dos.write(("r" + rotation + "\n").getBytes());
//			dos.flush();
//			dos.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
}